<?php
class model_UserMapper {
    private $table = 'users';
    private $message;

    public function  __construct() {
        model_ConfigMapper::connect();
    }

    public  function setMessage($message) {
        $this->message .= $message;
    }

    public  function getMessage() {
        return $this->message;
    }

    public function getTable() {
        return $this->table;
    }

    function validateReg($allSubmitted) {
        //проверка на совпадение паролей в форме/на существование такого же имени
        //если какяа либо из этих ошибок присутствует - записываем её в месседж, который после выдаем пользователю

        $password = $allSubmitted["password"];
        $rpassword = $allSubmitted["rpassword"];

        if ($password != $rpassword) {
            $this->setMessage("<p>Пароли не совпадают!</p>");
        }

        $query = 'select * from '. $this->table; //TODO: обойтись без обхода, а выбирать напрямую эту строку и смотреть, существует ли результат
        $result = mysql_query($query);

        while ($row = mysql_fetch_array($result)) {
            if($row['username'] == $_POST['username']) {
                $this->setMessage("<p>Пользователь с таким именем уже существует, попробуйте другое имя</p>");
            }
        }

        return $this->message;
    }

    public function save($model) {

        if (0 == $model->getId()) {//сохраняем новую
            $query = 'INSERT INTO '. $this->table .' (username, password, role, salt, karma, sex, name, surname, avatar, about, age) VALUES ("'
                    . $model->getUsername() .'","'
                    . $model->getPassword() .'","'
                    . $model->getRole() .'","'
                    . $model->getSalt() .'","'
                    . $model->getKarma() .'","'
                    . $model->getSex() .'","'
                    . $model->getName() .'","'
                    . $model->getSurname() .'","'
                    . $model->getAvatar() .'","'
                    . $model->getAbout() .'","'
                    . $model->getAge() .'")';
            
            $result = mysql_query($query);

            $timer = model_ConfigMapper::instance();
            $timer->setSqlCounter();
        } else {
            if (null != $model->getPassword()) {
                $query = 'UPDATE '.$this->table.' SET password="'. $model->getPassword() .'", salt="'. $model->getSalt() .'" WHERE id="'. $model->getId() .'"' ;
                $result = mysql_query($query);

                $timer = model_ConfigMapper::instance();
                $timer->setSqlCounter();
            }
            if (null != $model->getName()) {
                $query = 'UPDATE '.$this->table.' SET name="'. $model->getName() .'" WHERE id="'. $model->getId() .'"' ;
                $result = mysql_query($query);

                $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();
            }
            if (null != $model->getSurname()) {
                $query = 'UPDATE '.$this->table.' SET surname="'. $model->getSurname() .'" WHERE id="'. $model->getId() .'"' ;
                $result = mysql_query($query);

                $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();
            }
            if (null != $model->getAbout()) {
                $query = 'UPDATE '.$this->table.' SET about="'. $model->getAbout() .'" WHERE id="'. $model->getId() .'"' ;
                $result = mysql_query($query);

                $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();
            }
            if (null != $model->getAge()) {
                $query = 'UPDATE '.$this->table.' SET age="'. $model->getAge() .'" WHERE id="'. $model->getId() .'"' ;
                $result = mysql_query($query);

                $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();
            }
        }
    }

    public function saveAvatar($avatar, $id) {
        $query = 'UPDATE '.$this->table.' SET avatar="'. $avatar .'" WHERE id="'. $id .'"' ;
        $result = mysql_query($query);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();
    }

    public function login($model) {
        $query = 'SELECT * from '. $this->table ;
        $result = mysql_query($query);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();

        while ($row = mysql_fetch_assoc($result)) {
            if($row['username'] == $model->getUsername()) {
                $pass = md5($row['salt'].$model->getPassword());

                if ($row['password'] == $pass) {
                    if('banned' != $row['role']) {
                        if(empty($_SESSION)) {
                            session_start();
                        }
                        $_SESSION['id'] = $row['id'];
                    } else {
                        $this->setMessage('Вы забанены, а значит можете пользоваться только общедоступными функциями.');
                    }
                } else {
                    $this->setMessage('Вы ввели неверный пароль, попробуйте ещё раз.');
                }
            }
        }
        if (empty($_SESSION) && empty($this->message)) {
            $this->setMessage('Вы ввели неверный логин, попробуйте ещё раз.');
        }
    }

    public function fastLogin($model, $id) {
        if(empty($_SESSION)) {
            session_start();
        }
        $_SESSION['id'] = $id; // почему то не смотрит айди
    }

    public function logoff() {
        session_start();
        unset($_SESSION['id']);
        session_destroy();
    }

    public static function getCurrentUser() {

        if(empty($_SESSION)) {
            session_start();
            if (empty($_SESSION['id'])) {
                $_SESSION['id'] = 'no';
            }
        }

        if('no' != $_SESSION['id']) {
            $id = $_SESSION['id'];

            model_ConfigMapper::connect();

            $query = 'SELECT * from users WHERE id = '. $id;
            $result = mysql_query($query);
            $row = mysql_fetch_array($result);

            $timer = model_ConfigMapper::instance();
            $timer->setSqlCounter();

            $user = new model_UserModel($row);

            return $user;
        } else {
            $user = new model_UserModel();
            return $user;
        }
    }

    public function find($id) {
        $query = 'SELECT * from '. $this->table .' WHERE id = '. $id;

        $result = mysql_query($query);
        $row = mysql_fetch_array($result);

        if ($row) {
            $m = new model_UserModel($row);
        } else {
            $m = new model_UserModel(null);
        }

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();
        
        return $m;
    }

    public function fetchAll($start = null, $nums = null) {
        if (!empty($nums)){
            $query = 'SELECT * from '. $this->table .' ORDER BY id ASC LIMIT '. $start .', '. $nums ;
        } else {
            $query = 'SELECT * from '. $this->table .' ORDER BY id ASC';
        }

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();
        
        $result = mysql_query($query);

        $entries = array();

        while ($row = mysql_fetch_assoc($result)) {
            $entry = new model_UserModel($row);
            $entries[] = $entry;
        }
        return $entries;
    }

    public function delete($id) { // удаление пользователя влечет каскадное удаление всех его новостей и комментов
        $query = 'DELETE FROM '. $this->table .' WHERE id='. $id;
        $result = mysql_query($query);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();

        $query = 'SELECT id from news Where author ='. $id;
        $result = mysql_query($query);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();

        while ($row = mysql_fetch_assoc($result)) { //удаляем все связи тегов с сообщениями пользователя
            $query = 'DELETE FROM tagtonews WHERE newsid='. $row['id'] ;
            $result = mysql_query($query);

            $timer = model_ConfigMapper::instance();
            $timer->setSqlCounter();
        }

        $query = 'DELETE FROM news WHERE author='. $id ; //удаляем все посты на стену пользователя
        $result = mysql_query($query);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();
        
        $query = 'DELETE FROM comments WHERE author='. $id ; //удаляем все комменты пользователя
        $result = mysql_query($query);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();
        
        $query = 'DELETE FROM messages WHERE kto='. $id ; //удаляем все исходящие личные сообщения пользователя
        $result = mysql_query($query);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();

        $query = 'DELETE FROM messages WHERE komu='. $id ; //удаляем все входящие сообщения пользователя
        $result = mysql_query($query);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();

        $query = 'SELECT name FROM photos WHERE owner='. $id ;
        $result = mysql_query($query);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();

        while ($row = mysql_fetch_assoc($result)) { //удаляем все картинки пользователя
            unlink('stuff/images/saved/'. $row['name'] .'.jpg');
        }

        $query = 'DELETE FROM photos WHERE owner='. $id ;
        $result = mysql_query($query);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();
    }

    public function ban($id) {
        $query = 'UPDATE '. $this->table .' SET role = "banned" WHERE id='. $id ;
        $result = mysql_query($query);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();
    }

    public function unban($id) {
        $query = 'UPDATE '. $this->table .' SET role = "user" WHERE id='. $id ;
        $result = mysql_query($query);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();
    }

    public function filter($post) {
        $query = 'SELECT * from '. $this->table .' WHERE';

            if ('' != $post['name']) {
                $query .= ' ( username LIKE "'. $post['name'] .'%" OR
                    name LIKE "'. $post['name'] .'%" OR
                    surname LIKE "'. $post['name'] .'%" ) AND';
            }

            if (!empty($post['sex'])) {
                $query .= ' sex = "'. $post['sex'] .'" AND';
            }

            if (0 != $post['fromage']) {
                    $query .= ' age >= "'. $post['fromage'] .'" AND';
                }
                if (0 != $post['toage']) {
                    $query .= ' age > 0 AND age <= "'. $post['toage']. '"';
                }

        $query = rtrim($query, ' AND');
        $result = mysql_query($query);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();

        $entries = array();

        while ($row = mysql_fetch_assoc($result)) {

            $query = 'SELECT * from news WHERE author = '. $row['id'];

            $res = mysql_query($query);

            $timer = model_ConfigMapper::instance();
            $timer->setSqlCounter();

            while ($r = mysql_fetch_assoc($res)) {
                $entry = new model_NewsModel($r);
                $entries[] = $entry;
            }
        }
        return $entries;
    }
}